package ch.unisi.inf.projects.java.uom.gui.itemeditor.fieldselector;

import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.BoxLayout;
import javax.swing.Box;
import java.awt.Color;
import java.util.List;
import java.util.ArrayList;
import java.awt.GridLayout;
import java.awt.FlowLayout;

import ch.unisi.inf.projects.java.uom.Constants;
import ch.unisi.inf.projects.java.uom.Parser;
import ch.unisi.inf.projects.java.uom.elements.ItemManager;
import ch.unisi.inf.projects.java.uom.exceptions.UOMException;
import ch.unisi.inf.projects.java.uom.elements.Item;
import ch.unisi.inf.projects.java.uom.elements.ItemClass;
import ch.unisi.inf.projects.java.uom.gui.UOMMainFrame;
import ch.unisi.inf.projects.java.uom.gui.UOMImages;
import ch.unisi.inf.projects.java.uom.gui.commands.IconedCommand;

public class ListEntryGUIDialog extends JDialog {

	/** We are not going to serialize this class atm */
	private static final long serialVersionUID = -1L;
	
	private final Item item;
		
	private final String key;
	
	private final String value;
	
	private boolean isItemRel;
	
	private final JPanel entriesPanel;
	
	private final ListEntryGUIDialog dialog;
	
	private final List<EntryGUI> entries;
	
	private static JButton addButton;
	
	private static JButton saveButton;
	
	private static JButton closeButton;
	
	{
		addButton = new JButton(new IconedCommand ("", "Add a new Entry", UOMImages.ADD.getFileName()) {
			private static final long serialVersionUID = -1L;
			public void actionPerformed (final ActionEvent ev) { createNewEntry(""); }
		});
		saveButton = new JButton(new IconedCommand ("", "Save the list", UOMImages.OK.getFileName()) {
			private static final long serialVersionUID = -1L;
			public void actionPerformed (final ActionEvent ev) { UOMMainFrame.instance().setEnabled(true); save(); dispose(); }
		});
		closeButton = new JButton(new IconedCommand ("", "Cancel", UOMImages.CANCEL.getFileName()) {
			private static final long serialVersionUID = -1L;
			public void actionPerformed (final ActionEvent ev) { UOMMainFrame.instance().setEnabled(true); ItemManager.instance().elementSetField(item, key, value); dispose(); }
		});
	}
	
	public ListEntryGUIDialog (final Item item, final String key, final String value)
	{
		super();
		this.dialog = this;
		this.item = item;
		this.key = key;
		this.value = item.getField(key);
		entriesPanel = new JPanel();
		entriesPanel.setLayout(new GridLayout(0,2));
		entries = new ArrayList<EntryGUI>();
		this.getContentPane().setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS));
		try {
			this.setTitle("List of " + Parser.instance().dbGetListTypeVar(key));
			final String rel = Parser.instance().dbGetListTypeRelationship(key);
			if (!rel.equals(Constants.ITEM_CLASS_STRING.value()))
				isItemRel = true;
		}
		catch (final UOMException uome) {
			this.setTitle("List of elements");
		}
		try {
			final String className = Parser.instance().dbGetListTypeRelationship(key);
			if (!className.equals(Constants.ITEM_CLASS_STRING.value())) {
				final ItemClass c = ItemManager.instance().itemClassGet(className);
				if (c == null)
					return;
			}
		}
		catch (final Exception ex) {
			return;
		}
		this.setResizable(false);
		this.setBackground(Color.WHITE);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		UOMMainFrame.instance().setEnabled(false);
		this.addWindowListener(new WindowAdapter() {
			public void windowClosed (final WindowEvent ev) { UOMMainFrame.instance().setEnabled(true); }
		});
		this.getContentPane().add(entriesPanel);
		makeDialog();
		this.setLocationRelativeTo(null);
		this.setVisible(true);
	}
	
	public void makeDialog ()
	{
		if (value != null && value != "") {
			final String[] references = value.split(Constants.ITEM_PARSECHAR.value());
			for (final String ref : references) {
				if (!ref.equals(""))
					createNewEntry(ref);
			}
		}
		final JPanel commandsPanel = new JPanel();
		commandsPanel.setLayout(new FlowLayout());
		commandsPanel.add(addButton);
		commandsPanel.add(Box.createHorizontalStrut(10));
		commandsPanel.add(saveButton);
		commandsPanel.add(Box.createHorizontalStrut(10));
		commandsPanel.add(closeButton);
		commandsPanel.setBackground(Color.WHITE);
		this.getContentPane().add(commandsPanel);
		pack();
	}
		
	private void createNewEntry (final String val)
	{
		final JPanel panel = new JPanel();
		panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
		panel.add(Box.createVerticalGlue());
		final EntryGUI entry;
		panel.setBackground(Color.WHITE);
		if (isItemRel) {
			String rel = "";
			try {
				rel = Parser.instance().dbGetListTypeRelationship(key);
			}
			catch (final UOMException uome) { }
			entry = new ItemEntryGUI(rel,val,panel,item);
			entries.add(entry);
		}
		else {
			final JPanel textPanel = new JPanel();
			textPanel.setLayout(new BoxLayout(textPanel, BoxLayout.X_AXIS));
			textPanel.add(Box.createHorizontalStrut(5));
			entry = new StringEntryGUI(null,val,textPanel,item);
			panel.add(textPanel);
			entries.add(entry);
		}
		panel.add(Box.createVerticalGlue());
		entriesPanel.add(panel);
		final JButton delete = new JButton();
		final JPanel deletePanel = new JPanel();
		delete.setAction(new IconedCommand ("", "Delete this Entry", UOMImages.REMOVE.getFileName()) {
			private static final long serialVersionUID = -1L;
			public void actionPerformed (final ActionEvent ev) { entries.remove(entry); entriesPanel.remove(panel); entriesPanel.remove(deletePanel); entriesPanel.revalidate(); entriesPanel.repaint(); dialog.pack(); }
		});
		deletePanel.setLayout(new BoxLayout(deletePanel, BoxLayout.Y_AXIS));
		deletePanel.add(Box.createVerticalGlue());
		deletePanel.add(delete);
		deletePanel.add(Box.createVerticalGlue());
		entriesPanel.add(deletePanel);
		pack();
		this.repaint();
	}
	
	private void save () {
		String values = new String();
		for(final EntryGUI e : entries)
		{
			final boolean isCorrect = e.setFromInput();
			if (!isCorrect)
				continue;
			if (!e.getValue().equals("")) {
				final String val;
				if (isItemRel) {
					val = e.getValue().split(Constants.ITEM_PARSECHAR.value())[1];
				}
				else {
					val = e.getValue();
				}
				if (val.equals(""))
					continue;
				values += val + Constants.ITEM_PARSECHAR.value();
			}
		}
		if (values.length() <= 1)
			values = "";
		else
			values = values.substring(0, values.length() - 1);
		ItemManager.instance().elementSetField(item, key, values);
	}
}